package cn.itcast.service.impl;

import cn.itcast.domain.Company;
import cn.itcast.domain.Course;
import cn.itcast.factory.MapperFactory;
import cn.itcast.mapper.CompanyMappe;
import cn.itcast.mapper.CourseMapper;
import cn.itcast.mapper.UserMapper;
import cn.itcast.service.CourseService;
import cn.itcast.utils.TransactionUtil;
import cn.itcast.utils.UuidUtils;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class CourseServiceImpl implements CourseService {
    @Override
    public List<Course> findAll(int pageNum) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        PageHelper.startPage(pageNum, 5);
         List<Course> courseList = mapper.findAll();
        //释放资源
        TransactionUtil.close(sqlSession);
        return courseList;
    }

    @Override
    public void add(Course course) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        course.setId(UuidUtils.getUuid());
        course.setCreateTime(new Date());
        mapper.add(course);

        //释放资源
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);

    }

    @Override
    public Course findById(String id) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
         Course course = mapper.findById(id);
        //释放资源
        TransactionUtil.close(sqlSession);
        return course;
    }

    @Override
    public void edit(Course course) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);

        mapper.edit(course);

        //释放资源
        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }

    @Override
    public void deleteByIds(String ids) {
        //获取session
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取mapper对象


        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);

        if (ids != null && ids.length()>0){
            String[] sts = ids.split(",");
            mapper.deleteByIds(sts);
        }

        TransactionUtil.commit(sqlSession);
        TransactionUtil.close(sqlSession);
    }
}
